package com.example.diagnose.Controller;

import cn.hutool.json.JSONUtil;
import com.example.diagnose.Config.*;
import com.example.diagnose.Domain.BaiduChatMessage;
import com.example.diagnose.Domain.DiagnoseRecord;
import com.example.diagnose.Dto.Content;
import com.example.diagnose.Service.BaiduService;
import com.example.diagnose.Service.DiagnoseRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/diagnose_api")
@Tag(name = "对话接口模块")
public class ApiController {
    static String appKey = "NLPfdMqKmWv05VbGpraBDPTN";
    static String secretKey = "T0Jwbk081B2VHF2QHYlHxeCzoigkAgn8";

    BaiduService baiduService = new BaiduService(appKey, secretKey);

    @Resource
    DiagnoseRecordService diagnoseRecordService;

    @Operation(summary = "请求同步回答")
    @PostMapping
    public ErnieBotTurboResponse getResponse(@RequestBody Content content) {

        // 1. 构建请求体
        // 1.1 调用API，要从数据库去查询上下文
        DiagnoseRecord dr = diagnoseRecordService.getDiagnoseRecordByAccountLatest(content.getAccount());
        String records = dr == null ? "{}" : dr.getRecord_link();
        // 1.2 把message加进请求体
        // 1.2.1 解析上下文，获取聊天记录，把新的message封装加入到聊天记录中
        ErnieBotTurboStreamParam param = JSONUtil.toBean(records, ErnieBotTurboStreamParam.class);
        List<BaiduChatMessage> messages = param.getMessages() == null ? new ArrayList<>() : param.getMessages();
        messages.add(BaiduChatMessage.builder().role(ChatRoleConstant.USER).content(content.getContent()).build());
        // 1.2.2 把messages重新设置到param中
        param.setMessages(messages);
        param.setTemperature(0.95F);
        param.setPenalty_score(1.0F);
        param.setTop_p(0.8F);
        param.setUser_id(content.getAccount());
        param.setSystem();
        System.out.println(param);
        ErnieBotTurboResponse response = baiduService.ernieBotTurbo(param);

        // 2.刚返回的回复追加到param中，再填入chatRecord
        BaiduChatMessage aiMessage = BaiduChatMessage.builder()
                .role(ChatRoleConstant.ASSISTANT).content(response.getResult()).build();
        messages.add(aiMessage);
        param.setMessages(messages);

        if (dr == null) {
            // 3.1 如果没有记录，则插入
            DiagnoseRecord record = new DiagnoseRecord();
            record.setUser_account(content.getAccount());
            record.setRecord_link(JSONUtil.toJsonStr(param));
            record.setTime(LocalDateTime.now());
            record.setRecord_title(content.getContent());
            diagnoseRecordService.addDiagnoseRecord(record);
        } else {
            // 3.2 如果有记录
            // 先查询出原来的记录的create_time，判断是否超过15min
            LocalDateTime createTime = dr.getTime();
            if (LocalDateTime.now().isAfter(createTime.plusMinutes(15))) {
                // 如果超过15min，则将新的对话记录加到数据库中
                DiagnoseRecord record = new DiagnoseRecord();
                record.setUser_account(content.getAccount());

                //新开对话记录
                List<BaiduChatMessage> newMessages = new ArrayList<>();
                newMessages.add(BaiduChatMessage.builder().role(ChatRoleConstant.USER).content(content.getContent()).build());
                newMessages.add(aiMessage);
                param.setMessages(newMessages);
                record.setRecord_link(JSONUtil.toJsonStr(param));

                record.setTime(LocalDateTime.now());
                record.setRecord_title(content.getContent());
                diagnoseRecordService.addDiagnoseRecord(record);
            } else {
                // 如果没有超过15min，则将新的对话记录追加到records字段中
                ErnieBotTurboStreamParam newRecord = JSONUtil.toBean(dr.getRecord_link(), ErnieBotTurboStreamParam.class);
                // 将新的对话记录追加到records字段中
                newRecord.setMessages(messages);
                dr.setRecord_link(JSONUtil.toJsonStr(newRecord));
                // 更新chat_record
                diagnoseRecordService.updateDiagnoseRecord(dr);
            }

        }
        return response;
    }

//    @Operation(summary = "请求流式回答")
//    @PostMapping("/stream")
//    public void getStreamResponse(@RequestBody Content content) {
//        ErnieBotTurboStreamParam param = ErnieBotTurboStreamParam.builder()
//                .messages(Collections.singletonList(BaiduChatMessage.builder()
//                        .role(ChatRoleConstant.USER)
//                        .content(content.getContent())
//                        .build()))
//                .temperature(0.95F)
//                .penalty_score(1.0F)
//                .top_p(0.8F)
//                .user_id(content.getAccount())
//                .build();
//        param.setSystem();
//        baiduService.ernieBotTurboStream(param, new BaiduEventSourceListener());
////        while (true) {
////        }
//    }

    @Operation(summary = "请求中医同步回答")
    @PostMapping("/chinese")
    public ErnieBotTurboResponse getChResponse(@RequestBody Content content) {
        // 1. 构建请求体
        // 1.1 调用API，要从数据库去查询上下文
        DiagnoseRecord dr = diagnoseRecordService.getDiagnoseRecordByAccountLatest(content.getAccount());
        String records = dr == null ? "{}" : dr.getRecord_link();
        // 1.2 把message加进请求体
        // 1.2.1 解析上下文，获取聊天记录，把新的message封装加入到聊天记录中
        ErnieBotTurboStreamParam param = JSONUtil.toBean(records, ErnieBotTurboStreamParam.class);
        List<BaiduChatMessage> messages = param.getMessages() == null ? new ArrayList<>() : param.getMessages();
        messages.add(BaiduChatMessage.builder().role(ChatRoleConstant.USER).content(content.getContent()).build());
        // 1.2.2 把messages重新设置到param中
        param.setMessages(messages);
        param.setTemperature(0.95F);
        param.setPenalty_score(1.0F);
        param.setTop_p(0.8F);
        param.setUser_id(content.getAccount());
        param.changeSystemToCh();
        System.out.println(param);
        ErnieBotTurboResponse response = baiduService.ernieBotTurbo(param);

        // 2.刚返回的回复追加到param中，再填入chatRecord
        BaiduChatMessage aiMessage = BaiduChatMessage.builder()
                .role(ChatRoleConstant.ASSISTANT).content(response.getResult()).build();
        messages.add(aiMessage);
        param.setMessages(messages);

        if (dr == null) {
            // 3.1 如果没有记录，则插入
            DiagnoseRecord record = new DiagnoseRecord();
            record.setUser_account(content.getAccount());
            record.setRecord_link(JSONUtil.toJsonStr(param));
            record.setTime(LocalDateTime.now());
            record.setRecord_title(content.getContent());
            diagnoseRecordService.addDiagnoseRecord(record);
        } else {
            // 3.2 如果有记录
            // 先查询出原来的记录的create_time，判断是否超过15min
            LocalDateTime createTime = dr.getTime();
            if (LocalDateTime.now().isAfter(createTime.plusMinutes(15))) {
                // 如果超过15min，则将新的对话记录加到数据库中
                DiagnoseRecord record = new DiagnoseRecord();
                record.setUser_account(content.getAccount());

                //新开对话记录
                List<BaiduChatMessage> newMessages = new ArrayList<>();
                newMessages.add(BaiduChatMessage.builder().role(ChatRoleConstant.USER).content(content.getContent()).build());
                newMessages.add(aiMessage);
                param.setMessages(newMessages);
                record.setRecord_link(JSONUtil.toJsonStr(param));

                record.setTime(LocalDateTime.now());
                record.setRecord_title(content.getContent());
                diagnoseRecordService.addDiagnoseRecord(record);
            } else {
                // 如果没有超过15min，则将新的对话记录追加到records字段中
                ErnieBotTurboStreamParam newRecord = JSONUtil.toBean(dr.getRecord_link(), ErnieBotTurboStreamParam.class);
                // 将新的对话记录追加到records字段中
                newRecord.setMessages(messages);
                dr.setRecord_link(JSONUtil.toJsonStr(newRecord));
                // 更新chat_record
                diagnoseRecordService.updateDiagnoseRecord(dr);
            }

        }
        return response;
    }

//    @Operation(summary = "请求中医流式回答")
//    @PostMapping("/chinese_stream")
//    public void getChStreamResponse(@RequestBody Content content) {
//        ErnieBotTurboStreamParam param = ErnieBotTurboStreamParam.builder()
//                .messages(Collections.singletonList(BaiduChatMessage.builder()
//                        .role(ChatRoleConstant.USER)
//                        .content(content.getContent())
//                        .build()))
//                .temperature(0.95F)
//                .penalty_score(1.0F)
//                .top_p(0.8F)
//                .user_id(content.getAccount())
//                .build();
//        param.changeSystemToCh();
//        baiduService.ernieBotTurboStream(param, new BaiduEventSourceListener());
////        while (true) {
////        }
//    }
}
